﻿using CliWrap;

namespace FolderCompare;

public static class AppBase
{
    private static readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

    public static async void DeleteItems(CgFileSystemInfo[] items, CgDirectoryInfo currentDir, CgDirectoryInfo otherDir)
    {
        foreach (var item in items)
        {
            if (item is CgFileInfo file)
            {
                File.Delete(file.FullName);
            }
            else if (item is CgDirectoryInfo dir)
            {
                await DeleteDirectory(dir.FullName);
            }

            if (otherDir != null && otherDir.Children.HadItems())
            {
                var info2 = otherDir.Children.Single(s => s.Index == item.Index);

                if (info2.Name.IsNullOrEmpty())
                {
                    otherDir.Children.Remove(info2);
                    currentDir.Children?.Remove(item);
                }
                else
                {
                    var index = currentDir.Children!.IndexOf(item);
                    currentDir.Children.RemoveAt(index);

                    if (info2 is CgFileInfo fileInfo)
                    {
                        currentDir.Children.Insert(index, new CgFileInfo { Index = info2.Index, Result = ECompareResult.空 });
                        fileInfo.Result = ECompareResult.孤立;
                    }
                    else if (info2 is CgDirectoryInfo directoryInfo)
                    {
                        currentDir.Children.Insert(index, new CgDirectoryInfo { Index = info2.Index, Result = ECompareResult.空 });
                        directoryInfo.Result = ECompareResult.孤立;
                        CompareHelper.SetCompareResult(directoryInfo, ECompareResult.匹配);
                    }
                }
            }
        }

        currentDir.Result = CompareHelper.GetCompareResult(currentDir.Children);
        otherDir.Result = CompareHelper.GetCompareResult(otherDir.Children);
    }

    private static async Task DeleteDirectory(string fullName)
    {
        try
        {
            Directory.Delete(fullName, true);
        }
        catch (Exception ex)
        {
            _logger.Warn(ex);

            CommandResult result = await Cli.Wrap("cmd.exe")
                .WithArguments(new[] { "/C", "rd", "/s", "/q", fullName })
                .ExecuteAsync();
            _logger.Debug($"删除文件夹：{fullName}, {result.ExitCode}");
        }
    }

    public static string[]? ReadAllLines(string path)
    {
        if (File.Exists(path))
        {
            return File.ReadAllLines(path);
        }

        return null;
    }
}